<template>
  <div class="article-container">
    <SearchHead btnTitle="添加文章" searchTitle="请输入文章标题" @btnClick="addArtHandler" @onSearch="searchHandler"></SearchHead>
    <List :list="list" :listProp="listProp" @btnClick="emitOrDeleteHandler"></List>
     <Pagination @pageChange="update" :total="total"></Pagination>

    <div class="art-container" v-show="isEditArt">
      <div class="art-header">
        <div class="art-info">
          <div class="item">
            <span>文章标题:</span><el-input v-model="articleInfo.title"></el-input>
          </div>
          <div class="item">
            <span>文章描述:</span><el-input v-model="articleInfo.desc"></el-input>
          </div>
          <div class="item">
            <span>文章标签:</span><el-input @change="addTagHandler" v-model="tagVal"></el-input>
          </div>
          <div class="tagBox">
            <ul>
              <!-- 遍历生成tag标签 -->
              <li v-for="(item,index) in articleInfo.tag" :key="index">
                <el-tag @close="deleteTagHandler(index)" closable effect="dark" type="warning" size="large">{{item}}</el-tag>
              </li>
              
              
            </ul>
          </div>
        </div>
        <div class="imgUpload">
          <!-- 上传图片组件 -->
          <div class="pre-show" v-show="articleInfo.coverUrl">
            <img :src="$baseUrl + articleInfo.coverUrl" alt="">
          </div>
             <el-upload
                class="upload-demo"
                drag
                name="imgFile"
                :show-file-list="false"
                :action="$baseUrl + '/imgUpload'"
                :on-success="successHandler"
                >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>
        </div>
      </div>
      <div class="art-main">
        <mavon-editor ref="nd" @imgAdd="$imgAdd" v-model="articleInfo.contain"/>
      </div>
      <div class="art-footer">
        <el-button type="warning" @click="isEditArt=false">取消</el-button>
        <el-button type="success" @click="submit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import SearchHead from '../../../components/admin/SearchHead.vue'
import List from '../../../components/admin/List.vue'
import Pagination from '../../../components/admin/Pagination.vue'
import { Row } from 'element-ui'


  export default {
    components:{
      SearchHead,
      List,
      Pagination,
    },
    data() {
      return {
        list:[],
        listProp:[
          { label: '标题',prop: 'title'},
          { label: '标签',prop: 'tag'},
          { label: '日期',prop: 'createDate'},
          { label: '阅读',prop: 'readCount'},
          { label: '收藏',prop: 'foundCount'},
          { label: '评论',prop: 'commentCount'},
        ],
        total:2,
        isEditArt:false,
        submitType:'add',
        tagVal:'',
        // 传输文章内容标题对象
        articleInfo:{
        title:'',
        author:JSON.parse(localStorage.userInfo)._id,
        coverUrl:'/uploads/6a0902f957276bf6588a5b800.jpg',
        desc:'',
        tag:[],
        contain:'',
        }
      }
    },
    methods: {
      $imgAdd(pos,$file){
        // 第一步,将图片上传到服务器
        var formdata = new FormData()
        formdata.append('imgFile',$file)
        // 这里是发送请求的方法
        this.$http({
          url:'/imgUpload',
          method:'post',
          data:formdata,
          headers:{ 'Content-Type':'multipart/form-data'}
        }).then((res)=>{
          // 这里是上传成功后返回的url
          let url = res.data.url
          // 如果后期图片还显示不出来,用用正则表达式改变一下\\
          url = url.replace('\\','/')
          // 第二步  将返回的url替换到文本位置
      this.$refs.nd.$img2Url(pos,this.$baseUrl + url)
          // console.log(this.$refs);
        })
      },
      // 删除某一个标签
      deleteTagHandler(index){
        this.articleInfo.tag.splice(index,1)
      },
      // 添加标签
      addTagHandler(){
        this.articleInfo.tag.push(this.tagVal)
        this.tagVal=''
      },
      // 提交文章
      async submit(){
        let res
        if(this.submitType=='add'){
        this.articleInfo.createDate = +new Date()
        res = await this.$http.post('/artAdd',this.articleInfo) 
        }else{
          res = await this.$http.put('/artModify',this.articleInfo) 
        }
        const { status,data } = res
       if(status !=200) return this.$message.err(data.msg)
       this.$message.success(data.msg)
      this.isEditArt=false
      // 完成后重新获取新的数据
      this.getData()
      },


      // 决定添加文章界面显示按钮
      addArtHandler(){
        this.submitType='add'
        this.isEditArt=true

      },
      // 模糊查询操作
     async searchHandler(val){
     if(val){
         const { status,data } = await this.$http.get('/articleQuery?title=' + val)
           if(status!=200) return this.$message.error(data.msg)
          this.list=data.articleList
     }else{
      this.getData()
     }
      },  
      // 编辑或者删除文章
      emitOrDeleteHandler(type,row){
        if(type=='edit'){
          // 处理文章编辑
          this.isEditArt=true
          this.submitType='edit'
          this.articleInfo=JSON.parse(JSON.stringify(row))
        }else{
          // 执行删除文章
           this.$confirm('此操作将永久删除该文章, 是否继续?', '提示', {
          type: 'warning'
        }).then(async () => {
          const { status,data } = await this.$http.delete('/articleDelete?id=' + row._id)
           if(status!=200) return this.$message.error(data.msg)
           this.$message.success(data.msg)
           this.getData()
        }).catch(() => {
        });
        }
      },
      update(){

      },
      // 图片上传成功的回调函数
      successHandler(res){
        this.articleInfo.coverUrl=res.url

      },
       // 封装请求数据的方法
     async getData(page=1){
      const { status,data} = await this.$http.get('/articleList?page='+page)
      if(status!=200) return this.$message.error(data.msg)
      this.list = data.artList
      this.total=data.total
    },
    // 刷新标签页面内容
    update(page){
      this.getData(page)
    }
    },
    created() {
      this.getData()
    },
  }
</script>
<style>
  .el-upload-dragger{
    width: 220px;
    height: 170px;
    /* background-color: pink; */
  }
</style>

<style lang="less" scoped>
.tagBox{
padding-left: 83px;
padding-top: 10px;
  li{
    float:left ;
    margin-right: 10px;
    list-style-type: none;
  }
}
.article-container{
  position: relative;
}
.art-container{
position: absolute;
top: -20px;
left: 0;
width:100%;
min-height: 72vh;
padding: 0 30px 0 15px;
z-index: 99;
background-color: #fff;
box-sizing: border-box;
.art-header{
  overflow: hidden;
}
.art-info{
  float: left;
  .item{
  margin: 10px 0;
  margin-right:15px ;
    .el-input{
      width: 400px;
      margin-left: 15px;
    }
    }

}
.imgUpload{
  position: relative;
  float:right ;
  margin-right: 50px;
  // background-color: red;
   &:hover .pre-show{
      display: none;
    }
  .pre-show{
    position: absolute;
    top: 0;
    right: 0;
    width: 220px;
    height: 170px;
    z-index: 100;
   
    img{
      width: 100%;
      height: 100%;
    }
  }
}
.art-main{
  margin-top: 20px;
}
.art-footer{
margin-top: 20px;
margin-left: 170px;
}
}
</style>